//
//  PhotoChooseView.m
//  GBKTrade
//
//  Created by admin on 2019/4/24.
//  Copyright © 2019 LionIT. All rights reserved.
//

#import "PhotoChooseView.h"

@interface PhotoChooseView ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) UILabel *statementLab;
@property (nonatomic, strong) UILabel *introduceLab;
@property (nonatomic, strong) UIImagePickerController *imagePicker;

@end

@implementation PhotoChooseView
{
    NSInteger choosePhotoFlag;//区分给那个button赋值
}
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    choosePhotoFlag = 0;
    UIView *backView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    backView.backgroundColor = MainBackgroundColor;
    [self addSubview:backView];
    
    self.statementLab = [[UILabel alloc] init];
    self.statementLab.font = Font_15;
    self.statementLab.textAlignment = NSTextAlignmentLeft;
    self.statementLab.text = @"本人身份证照片认证";
    [backView addSubview:self.statementLab];
    [self.statementLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_offset(@(FIT(16)));
        make.height.mas_offset(@20);
        make.width.mas_offset(@(ScreenWidth-32));
    }];
    
    NSArray *imageArr = @[@[@"zheng_back",@"fan_back"],@[@"shouchi_back",@""]];
    NSArray *titleArr = @[@[@"点击上传证件正面照",@"点击上传证件反面照"],@[@"点击上传手持证件正面照",
                          @"1.请按照要求上传您的证件照片\n 2.仅支持jpg、bmp、png格式\n 3.大小限制为10M以内\n 4.确保身份证上的信息没被遮挡\n 5.避免证件与头部重叠\n 6.确保身份证内容完整清晰可见"]];
//    NSArray *imageArr = @[@"zheng_back",@"fan_back",@"shouchi_back"];
//    NSArray *titleArr = @[@"点击上传证件正面照",@"点击上传证件反面照",@"点击上传手持证件正面照"];
//    int hengNum = 2;
//    int shuNum = 2;
//    for (NSInteger i = 0; i < 3; i++) {
//        UIButton *button = [YQViewFactory buttonWithImage:YQ_IMAGE(imageArr[i]) target:self sel:@selector(addPhotoAction:)];
//        button.tag = 200+i;
//    }
    
    
    for (NSInteger i = 0; i < 2; i++) {
        for (NSInteger j = 0; j < 2; j++) {
            //i为横 j为竖
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [btn setBackgroundImage:YQ_IMAGE(imageArr[i][j]) forState:UIControlStateNormal];
            btn.frame = CGRectMake(16+(ScreenWidth-48)/2.0*j+16*j, FIT(52)+96*i+30*i, (ScreenWidth-48)/2.0, 96);
            [backView addSubview:btn];

            UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [addBtn setImage:YQ_IMAGE(@"add_id_card_bg") forState:UIControlStateNormal];
//            [addBtn setTitle:titleArr[i][j] forState:UIControlStateNormal];
            addBtn.frame = CGRectMake(16+(ScreenWidth-48)/2.0*j+16*j, FIT(52)+96*i+30*i, (ScreenWidth-48)/2.0, 96);
//            [addBtn setIconInTopWithSpacing:5];
            [addBtn addTarget:self action:@selector(addPhotoAction:) forControlEvents:UIControlEventTouchUpInside];
            [backView addSubview:addBtn];

            UIView *btnBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, (ScreenWidth-48)/2.0, 96)];
            btnBackView.backgroundColor = [UIColor colorWithRed:102/255.0 green:106/255.0 blue:126/255.0 alpha:0.3];
            [btn addSubview:btnBackView];

            UILabel *titleLab = [[UILabel alloc] init];
            titleLab.text = titleArr[i][j];
            titleLab.font = [UIFont systemFontOfSize:14];
            titleLab.textColor = [UIColor grayColor];
            titleLab.textAlignment = NSTextAlignmentLeft;
            [backView addSubview:titleLab];
            [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(@(16+(ScreenWidth-48)/2.0*j+16*j));
                make.top.mas_equalTo(btn.mas_bottom).mas_offset(@5);
                make.width.mas_offset(@((ScreenWidth-48)/2.0));
                make.height.mas_offset(@20);
            }];

            if (i == 0 && j == 0) {
                self.positivePhotoBtn = addBtn;
                addBtn.tag = 200;
            }else if (i == 0 && j == 1) {
                self.reversePhotoBtn = addBtn;
                addBtn.tag = 201;
            }else if (i == 1 && j == 0) {
                self.handheldPhotoBtn = addBtn;
                addBtn.tag = 202;
            }else {
                self.titleBtn = btn;
                self.titleBtn.enabled = NO;
                btnBackView.backgroundColor = [UIColor clearColor];
                [addBtn setImage:YQ_IMAGE(@"") forState:UIControlStateNormal];
                titleLab.hidden = YES;
                [addBtn setTitle:@"" forState:UIControlStateNormal];
                //创建说明label
                UILabel *desLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, (ScreenWidth-48)/2.0, 96)];
                desLab.numberOfLines = 6;
                desLab.text = @" 1.请按照要求上传您的证件照片\n 2.仅支持jpg、bmp、png格式\n 3.大小限制为10M以内\n 4.确保身份证上的信息没被遮挡\n 5.避免证件与头部重叠\n 6.确保身份证内容完整清晰可见";
                desLab.textAlignment = NSTextAlignmentLeft;
                desLab.textColor = [UIColor grayColor];
                desLab.font = [UIFont systemFontOfSize:10];
                [btn addSubview:desLab];
            }
        }
    }
    
    UIButton *commitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [commitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [commitBtn setTitleColor:WhiteColor forState:UIControlStateNormal];
    [commitBtn setBackgroundColor:MainRedTextColor];
    commitBtn.titleLabel.font = Font_15;
    commitBtn.layer.cornerRadius = 5.f;
    commitBtn.layer.masksToBounds = YES;
    [backView addSubview:commitBtn];
    self.commitBtn = commitBtn;

    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(@16);
        make.top.mas_equalTo(self.handheldPhotoBtn.mas_bottom).mas_offset(@65);
        make.width.mas_offset(@(ScreenWidth-32));
        make.height.mas_offset(@(FIT(60)));
    }];
}

- (void)addPhotoAction:(UIButton *)sender {

    choosePhotoFlag = sender.tag;
    DLog(@"choosePhotoFlag = %ld",sender.tag);
    //点击弹框选择照片 或者相机
    _imagePicker = [[UIImagePickerController alloc] init];
    _imagePicker.delegate = self;
    _imagePicker.allowsEditing = YES;
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"从相机拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [[self getCurrentVC] presentViewController:self.imagePicker animated:YES completion:nil];
            
        }
    }];
    
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [[self getCurrentVC] presentViewController:self.imagePicker animated:YES completion:nil];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了取消");
    }];
    
    [actionSheet addAction:cameraAction];
    [actionSheet addAction:photoAction];
    [actionSheet addAction:cancelAction];
    
    [[self getCurrentVC] presentViewController:actionSheet animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerController *,id> *)info {
    //获取图片
    UIImage *backImg = info[UIImagePickerControllerOriginalImage];
    if (choosePhotoFlag == 200) {
        [self selectedButtonWithTag:self.positivePhotoBtn senderImg:backImg withPicker:picker];
    }else if (choosePhotoFlag == 201) {
        [self selectedButtonWithTag:self.reversePhotoBtn senderImg:backImg withPicker:picker];
    }else if (choosePhotoFlag == 202) {
        [self selectedButtonWithTag:self.handheldPhotoBtn senderImg:backImg withPicker:picker];
    }
    
}

//按取消按钮时候的功能
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    // 返回
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 照片上传
- (void)selectedButtonWithTag:(UIButton *)btn senderImg:(UIImage *)backImg withPicker:(UIImagePickerController *)picker{
    DLog(@"btn.tag = %ld",btn.tag);
    [btn setBackgroundImage:backImg forState:UIControlStateNormal];
    [picker dismissViewControllerAnimated:YES completion:^{
        NSString* urlString=[NSString stringWithFormat:@"%@users/fileUpload",BaseHttpUrl];
        //把照片上传获取返回的URL
        [[SZHTTPSRsqManager sharedSZHTTPSRsqManager] postUploadWithUrl:urlString image:backImg successBlock:^(id responseObject) {
            //                resourceURL
            if (self.urlBlock) {
                self.urlBlock(responseObject[@"data"][@"resourceURL"], btn.tag);
                
            }
        } successBlock:^(NSError *error) {
            
        }];
    }];
    
}

#pragma mark - 获取当前view所添加的controller
- (UIViewController *)getCurrentVC
{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    return currentVC;
}

- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
    UIViewController *currentVC;
    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的
        rootVC = [rootVC presentedViewController];
    }
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
    } else {
        // 根视图为非导航类
        currentVC = rootVC;
    }
    return currentVC;
}

@end
